using System;
using System.Windows.Forms;
using CastleSample.Business.Client;
using CastleSample.Business.Interface;
using CastleSample.Entity;
using CastleSample.UI.Core;

namespace CastleSample.Modules.Order
{
    public partial class FormCreateOrder : Form, IToolStripForm
    {
        private bool m_IsDirty = false;

        private IOrderBizService m_OrderBizService;

        public IOrderBizService OrderBizService
        {
            get { return m_OrderBizService; }
            set { m_OrderBizService = value; }
        }

        public FormCreateOrder()
        {
            m_OrderBizService = BizServiceFactory.GetService<IOrderBizService>();
            InitializeComponent();
        }

        public ToolStrip MainToolStrip
        {
            get { return toolStripMain; }
        }

        private void numericUpDownNumberOfItems_ValueChanged(object sender, EventArgs e)
        {
            if (!m_IsDirty)
            {
                m_IsDirty = true;
                Text += " *";
                toolStripButtonSave.Enabled = true;
                toolStripMenuItemSave.Enabled = true;
            }
        }

        private void toolStripButtonCancel_Click(object sender, EventArgs e)
        {
            if (m_IsDirty)
            {
                DialogResult ret = MessageBox.Show(this, "Do you really want cancle the order creation?", "CastleSample", MessageBoxButtons.YesNo);
                if (ret == DialogResult.Yes)
                {
                    Close();
                }
            }
            else
            {
                Close();
            }
        }

        private void toolStripButtonSave_Click(object sender, EventArgs e)
        {
            if (numericUpDownNumberOfItems.Value > 10 || numericUpDownNumberOfItems.Value < 0)
            {
                MessageBox.Show(this, "Number of Order Items can not more than 10 or less than 0");
                return;
            }
            OrderEntity order = new OrderEntity();
            order.Status = OrderStatus.Confirmed;
            for (int i = 0; i < numericUpDownNumberOfItems.Value; i++)
            {
                OrderItemEntity item = new OrderItemEntity();
                item.ProductId = string.Format("Test Product {0}", i);
                item.Quantity = 3;
                item.Amount = 30;
                order.OrderItems.Add(item);
            }
            order = OrderBizService.CreateOrder(order);
            if (order != null)
            {
                ApplicationContainer.Instance.EventBroker.PublishEvent("OrderCreated", this, new ContainerEventArgs("OrderEntity", order));
                Close();
            }
            else
            {
                MessageBox.Show(this, "Create order failed!");
            }
        }
    }
}